package Servlet;

import bean.Problem;
import com.fasterxml.jackson.databind.ObjectMapper;
import dao.ProblemDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张
 * Date: 2025-01-23
 * Time: 17:03
 */
//这个路径即使获取列表也是获取详情的接口(根据参数进行区分)
@WebServlet("/problem")
public class ProblemServlet extends HttpServlet {
    private ProblemDao problemDao = new ProblemDao();
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Json格式的数据的Content-Type:application/json;charset=utf8 (固定的)
        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");

        // 尝试获取url中的id参数(如果获取的到就是获取题目详情,如果获取不到就是题目列表)
        String idString = req.getParameter("id");
        if(idString == null || "".equals(idString)) {
            //没有获取到id字段 --- 获取题目列表
            List<Problem> list = problemDao.selectAll();
            System.out.println("[ProblemServlet] 获取的题目列表数据为 : " + list.toString());
            //转换成json格式
            String respString = objectMapper.writeValueAsString(list);
            //设置http响应的body部分
            //http协议的报头要求通过Content-Length来描述body的长度(长度部分Servlet已经自动生成了)
            //通过Content-Type来表示body的类型
            resp.getWriter().write(respString);
        } else {
            //获取题目详情
            Problem problem = problemDao.selectOne(Integer.parseInt(idString));
            //转换成json结构
            String respString = objectMapper.writeValueAsString(problem);
            resp.getWriter().write(respString);
        }


    }
}
